﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.IO;
using System.Xml;
using System.Xml.Linq;

using Sogeti.QueryWrapper;
using Sogeti.SourceControlWrapper;
using System.ComponentModel;
using Sogeti.VSExtention;

namespace Mskold.IterationManager
{

    public class IterationManagerConfigStore : INotifyPropertyChanged
    {

        public  IterationManagerConfigStore(TeamExplorerIntergator te)
        {
            teamExplorer = te;
            NewIterationManualConfig = false;
        }

        #region Properties 

        public bool     NewIterationManualConfig
        {
            get { return _NewIterationManualConfig; }
            set
            {
                _NewIterationManualConfig = value;
                if (value == false)
                {
                     AssignAutoConfig(this);
                }
                NotifyPropertyChanged("NewIterationManualConfig");
            }
        }

        public bool     ChangeCurrentIteratonFolder
        {
            get { return _ChangeCurrentIteratonFolder; }
            set
            {
                _ChangeCurrentIteratonFolder = value;
                NotifyPropertyChanged("ChangeCurrentIteratonFolder");
            }
        }
        public String   CurrentIterationWIQLFolder
        {
            get { return _CurentIterationWIQLFolder; }
            set
            {
                _CurentIterationWIQLFolder = value;
                NotifyPropertyChanged("CurentIterationWIQLFolder");
            }
        }
 
        public bool     CreateSprintWorkItem    
        {
            get { return _CreateSprintWorkItem; }
            set
            {
                _CreateSprintWorkItem = value;
                NotifyPropertyChanged("CreateSprintWorkItem");
            }
        }
        public String   SprintWorkItemType
        {
            get { return _SprintWorkItemType; }
            set
            {
                _SprintWorkItemType = value;
                NotifyPropertyChanged("SprintWorkItemType");
            }
        }
        public String   SprintStartField
        {
            get { return _SprintStartField; }
            set
            {
                _SprintStartField = value;
                NotifyPropertyChanged("SprintStartField");
            }
        }
        public String   SprintFinishField
        {
            get { return _SprintFinishField; }
            set
            {
                _SprintFinishField = value;
                NotifyPropertyChanged("SprintFinishField");
            }
        }


        public bool     CreateSprintFolder         
        {
            get { return _CreateSprintFolder; }
            set
            {
                _CreateSprintFolder = value;
                NotifyPropertyChanged("CreateSprintFolder");
            }
        }
        public String   TempalteWIQLFolder
        {
            get { return _TempalteWIQLFolder; }
            set
            {
                _TempalteWIQLFolder = value;
                NotifyPropertyChanged("TempalteWIQLFolder");
            }
        }
      
        #endregion
        
        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;


        private void NotifyPropertyChanged(String info)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(info));
            }
        }
        #endregion
        
  


        internal XmlDocument Save()
        {


            List<XElement> lst= new List<XElement>();

            if (NewIterationManualConfig ) { 
                if (CreateSprintWorkItem)
                {
                    lst.Add(new XElement("CreateSprintWorkItem",
                                new XAttribute("SprintWorkItemType", SprintWorkItemType),
                                new XAttribute("SprintStartField", SprintStartField),
                                new XAttribute("SprintFinishField", SprintFinishField)
                        )
                    );
                }
                if(CreateSprintFolder)
                {
                    lst.Add(  
                            new XElement("CreateSprintFolder", 
                                new XAttribute("TemplateWIQLFolder", TempalteWIQLFolder))
                        );  
                }
                if (ChangeCurrentIteratonFolder)
                {
                    lst.Add(
                            new XElement("ChangeCurrentIteratonFolder",
                                new XAttribute("CurrentIterationWIQLFolder", CurrentIterationWIQLFolder))
                        );
                }
            }

            XDocument doc= new XDocument(
                new XElement("Config" ,
                    new XElement("NewIteration", new XAttribute("AutoConfig", !NewIterationManualConfig), 
                         lst
                    )
                )
           );
           
            
            XmlDocument xml= new XmlDocument();
            xml.LoadXml(doc.ToString());
            return xml;
        }

        internal void Load(XmlDocument xml)
        {
            XDocument doc = XDocument.Parse(xml.OuterXml);

            NewIterationManualConfig = doc.Element("Config").Element("NewIteration").Attribute("AutoConfig").Value=="false";      
            if(NewIterationManualConfig){
            
                XElement xCreateSprintElement = doc.Element("Config").Element("NewIteration").Element("CreateSprintWorkItem");

                CreateSprintWorkItem = xCreateSprintElement != null;

                if (CreateSprintWorkItem)
                {
                    SprintWorkItemType = xCreateSprintElement.Attribute("SprintWorkItemType").Value;
                    SprintStartField = xCreateSprintElement.Attribute("SprintStartField").Value;
                    SprintFinishField = xCreateSprintElement.Attribute("SprintFinishField").Value;
                }

                XElement xCreateFolderElement = doc.Element("Config").Element("NewIteration").Element("CreateSprintFolder");
                CreateSprintFolder = xCreateFolderElement != null;
                if (CreateSprintFolder)
                {
                    TempalteWIQLFolder = xCreateFolderElement.Attribute("TemplateWIQLFolder").Value;              
                }


                XElement xChangeCurrentIteratonFolderElement = doc.Element("Config").Element("NewIteration").Element("ChangeCurrentIteratonFolder");
                ChangeCurrentIteratonFolder = xChangeCurrentIteratonFolderElement != null;

                if (ChangeCurrentIteratonFolder)
                {
                    CurrentIterationWIQLFolder = xChangeCurrentIteratonFolderElement.Attribute("CurrentIterationWIQLFolder").Value;
                }
            }
        }

        public  void AssignAutoConfig(IterationManagerConfigStore autoStore)
        {
         
            TPWiWrapper wi = new TPWiWrapper(teamExplorer);
            if (wi.GetWorkItemTypes().Contains("Sprint"))
            {
                autoStore.CreateSprintWorkItem = true;
                autoStore.SprintWorkItemType = "Sprint";
                autoStore.SprintStartField = "Microsoft.VSTS.Scheduling.StartDate";
                autoStore.SprintFinishField = "Microsoft.VSTS.Scheduling.FinishDate";
            }
            else
            {
                autoStore.CreateSprintWorkItem = false;
                autoStore.SprintWorkItemType = "";
                autoStore.SprintStartField = "";
                autoStore.SprintFinishField = "";              
            }

         
            TPQueryWrapper qw = new TPQueryWrapper(teamExplorer);
            List<WiqlFolder> lst=  qw.ListFolders(teamExplorer.tpName + @"/Team Queries");
            
            WiqlFolder fldCurrentIteration=null;
            WiqlFolder fldIterationFolderTemplate= null;

            foreach (WiqlFolder f in lst)
            {
                if (f.Name == "Current Sprint")
                {
                    fldCurrentIteration = f;
                }
                if (f.Name == "Iteration 1")
                {
                    fldIterationFolderTemplate = f;
                }
            }

            autoStore.ChangeCurrentIteratonFolder = fldCurrentIteration != null;
            if (autoStore.ChangeCurrentIteratonFolder)
            {
                autoStore.CurrentIterationWIQLFolder = fldCurrentIteration.Path;
            }


            autoStore.CreateSprintFolder = fldIterationFolderTemplate != null;
            if (autoStore.CreateSprintFolder)
            {
                autoStore.TempalteWIQLFolder = fldIterationFolderTemplate.Path;
            }

        }

        private bool _NewIterationManualConfig;
        private string _TempalteWIQLFolder;
        private bool _CreateSprintWorkItem;
        private bool _CreateSprintFolder;
        private string _SprintStartField;
        private string _SprintWorkItemType;
        private string _SprintFinishField;

        private TeamExplorerIntergator teamExplorer;
        private string _CurentIterationWIQLFolder;
        private bool _ChangeCurrentIteratonFolder;

    }


    public class IterationManagerConfig 
    {
        public string _MODULE_CONFIG_FILE_NAME_ = @"/IterationManager.config";

        private TeamExplorerIntergator teamExplorer;
        private IterationManagerConfigStore _configStore;




        public IterationManagerConfigStore ConfigStore
        {
            get { return _configStore; }
            set { _configStore = value; }
        }

 
        public IterationManagerConfig(TeamExplorerIntergator teIntegrator)
        {
             teamExplorer= teIntegrator;
             ConfigStore = new IterationManagerConfigStore(teamExplorer);
        }

       
 


   


        public bool ConfigFileExist()
        {

            SCWrapper sc = new SCWrapper(teamExplorer);
            
            return sc.FileExist(sc.RootFolder() + _MODULE_CONFIG_FILE_NAME_);

        }
    
        public void Load()
        {

            SCWrapper sc = new SCWrapper(teamExplorer);

            if (sc.FileExist(sc.RootFolder() + _MODULE_CONFIG_FILE_NAME_))
            {
                Stream s = sc.Get(sc.RootFolder() + _MODULE_CONFIG_FILE_NAME_);
                XmlDocument xml = new XmlDocument();
                xml.Load(s);
                ConfigStore = new IterationManagerConfigStore(teamExplorer);
                ConfigStore.Load(xml);
            }

        }

        public void Save()
        {
            SCWrapper sc = new SCWrapper(teamExplorer);

            XmlDocument xml =      ConfigStore.Save();
            sc.Save(sc.RootFolder() + _MODULE_CONFIG_FILE_NAME_, xml);
        }


    }
}
